package com.lamp.connection;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import android.app.Activity;
import android.content.Context;
import android.util.Log;

public class ConnectionManager implements Runnable {

	Thread thread;
	public boolean isRunning = false;
	private String _url = "";
	private int _requestId = 0;
	private RequestManager _requestManager = null;
	private int _requestType;
	private Activity _currentActivity;
	public boolean isConnectedToServer = false;
	public boolean isGotGoodResult = false;
	public HttpResponse response;
	private String json = "";
	private Context context;
	private int r;
	List<NameValuePair> postParameters;
	List<List<NameValuePair>> _postParamersList = new ArrayList<List<NameValuePair>>();
	List<String> _urls = new ArrayList<String>();

	public void setRequestManager(RequestManager reqM) {
		_requestManager = reqM;
	}

	public Activity getCurrentActivity() {
		return _currentActivity;
	}

	public void setCurrentActivity(Activity currentActivity) {
		_currentActivity = currentActivity;
	}

	public String getJSON() {
		return json;
	}

	public String getUrl() {
		return _url;
	}

	public void setUrl(String url) {
		// //Log.println(Log.INFO, AppDefines.NRANGE_TAG, "Requested URL: " +
		// url);
		if (_requestManager.isRunning)
			_urls.add(url);
		else
			_url = url;
	}

	public void refresh() {
		_url = _urls.get(0);
		_urls.remove(0);
		postParameters = new ArrayList<NameValuePair>();
		postParameters = _postParamersList.get(0);
		// Log.d("params", postParameters.toString());
		_postParamersList.remove(0);
	}

	public void setParams(List<NameValuePair> params) {

		if (_requestManager.isRunning) {
			// Log.d("Param", "Param is add list");
			// Log.d("params", params.toString());
			_postParamersList.add(params);
		} else {
			postParameters = new ArrayList<NameValuePair>();
			postParameters = params;
		}
	}

	public ConnectionManager(Context context) {
		this.context = context;
	}

	public void setRequestType(int reqType) {
		this._requestType = reqType;
	}

	public void setRequestId(int reqId) {
		this._requestId = reqId;
	}

	public void run() {

		int reqType = _requestType;
		isConnectedToServer = false;
		isGotGoodResult = false;
		Log.d("Run", "Running........");
		for (r = 0; r < 2; r++) {
			HttpClient client = null;
			HttpPost request = null;
			BufferedReader in = null;
			try {
				Log.d("Run", "Running1........");
				client = new DefaultHttpClient();
				request = new HttpPost(_url);
				Log.d("Run", "Running2........");
				UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
						postParameters, HTTP.UTF_8);
				request.setEntity(formEntity);
				Log.d("Run", "Running3........");
				response = client.execute(request);
				in = new BufferedReader(new InputStreamReader(response
						.getEntity().getContent(), HTTP.UTF_8));

				String line = "";
				json = "";
				String buffer = "";
				while ((line = in.readLine()) != null) {

					json += line;
				}
				Log.d("JSON", json);
				Log.d("Response", response.getStatusLine().toString());

				if (response.getStatusLine().getStatusCode() == 200) {

					isConnectedToServer = true;
				} else {
					// //Log.println(Log.INFO, AppDefines.NRANGE_TAG,
					// "Response code:" + response);
				}
			} catch (Exception e) {
				Log.d("SocketException", "Catch Excetion");

			} finally {

				if (request != null) {
					try {
						request.abort();
						Log.d("Abort", "Aborted");
						Log.d("Response", response.getStatusLine().toString());
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
				if (in != null) {
					try {
						in.close();
					} catch (Exception e) {
						// //Log.println(Log.ERROR, AppDefines.NRANGE_TAG,
						// e.toString());
					}
				}

			}

			if (_requestManager.getRequestId() != _requestId) {
				// //Log.println(Log.INFO, AppDefines.NRANGE_TAG,
				// "Breaked by another request-#3");
				break;
			}

			if (isConnectedToServer) {
				// //Log.println(Log.INFO, AppDefines.NRANGE_TAG,
				// "Breaked by connected.");
				break;
			} else {
				if (reqType == RequestManager.REQUEST_NONE) {
					// //Log.println(Log.INFO, AppDefines.NRANGE_TAG,
					// "Breaked by app new version.");
					break;
				}
			}

			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				return;
			}
		}

		// //Log.println(Log.INFO, AppDefines.NRANGE_TAG, "End Millisec: " +
		// System.currentTimeMillis());
		isRunning = false;

	}

	public void start() {
		if (!isRunning) {
			try {
				isRunning = true;
				thread = new Thread(this);
				thread.start();
			} catch (Exception e) {
				isRunning = false;
			}
		}
	}

	public void stop() {
		if (isRunning == true) {
			try {
				thread.interrupt();
			} catch (Exception e) {
			}
		}
		isRunning = false;
	}

}
